package com.wtx.fitness.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wtx.fitness.common.Result;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.entity.Student;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.exception.NotFoundException;
import com.wtx.fitness.mapper.ScoreMapper;
import com.wtx.fitness.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 学生管理控制器
 */
@RestController
@RequestMapping("/api/student")
public class StudentController {

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private ScoreMapper scoreMapper;

  /**
   * 获取所有学生列表
   */
  @GetMapping("/list")
  public Result<List<Student>> getStudentList() {
    List<Student> students = studentMapper.list();
    // 出于安全考虑，不返回密码字段
    students.forEach(student -> student.setPassword(null));
    return Result.success(students);
  }

  /**
   * 根据学号获取学生信息
   */
  @GetMapping("/info/{stuId}")
  public Result<Student> getStudentInfo(@PathVariable String stuId) {
    Student student = studentMapper.findByStuId(stuId);
    if (student == null) {
      throw new NotFoundException("学生不存在");
    }
    // 出于安全考虑，不返回密码字段
    student.setPassword(null);
    return Result.success(student);
  }

  /**
   * 添加学生
   */
  @PostMapping("/add")
  public Result<Void> addStudent(@RequestBody Student student) {
    // 校验学号是否已存在
    if (studentMapper.findByStuId(student.getStuId()) != null) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "学号已存在");
    }

    // 设置默认密码为123456
    if (student.getPassword() == null || student.getPassword().isEmpty()) {
      student.setPassword("123456");
    }

    int rows = studentMapper.insert(student);
    if (rows <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "添加学生失败");
    }

    return Result.success();
  }

  /**
   * 更新学生信息
   */
  @PutMapping("/update/{stuId}")
  public Result<Void> updateStudent(@PathVariable String stuId, @RequestBody Student student) {
    // 校验学生是否存在
    if (studentMapper.findByStuId(stuId) == null) {
      throw new NotFoundException("学生不存在");
    }

    // 设置学号
    student.setStuId(stuId);

    // 不允许通过此接口修改密码
    student.setPassword(null);

    int rows = studentMapper.update(student);
    if (rows <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "更新学生信息失败");
    }

    return Result.success();
  }

  /**
   * 重置学生密码
   */
  @PostMapping("/reset-password/{stuId}")
  public Result<Void> resetPassword(@PathVariable String stuId) {
    // 校验学生是否存在
    if (studentMapper.findByStuId(stuId) == null) {
      throw new NotFoundException("学生不存在");
    }

    // 将密码重置为123456
    int rows = studentMapper.updatePassword(stuId, "123456");
    if (rows <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "重置密码失败");
    }

    return Result.success();
  }

  /**
   * 删除学生
   */
  @DeleteMapping("/delete/{stuId}")
  @Transactional
  public Result<Void> deleteStudent(@PathVariable String stuId) {
    // 校验学生是否存在
    if (studentMapper.findByStuId(stuId) == null) {
      throw new NotFoundException("学生不存在");
    }

    // 先删除该学生的所有成绩记录
    scoreMapper.deleteByStuId(stuId);

    // 然后删除学生
    int rows = studentMapper.deleteByStuId(stuId);
    if (rows <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "删除学生失败");
    }

    return Result.success();
  }

  /**
   * 批量导入学生
   */
  @PostMapping("/batch-import")
  public Result<Void> batchImportStudents(@RequestBody List<Student> students) {
    if (students == null || students.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "学生数据不能为空");
    }

    // 校验学生数据
    for (Student student : students) {
      // 必填字段校验
      if (student.getStuId() == null || student.getStuId().isEmpty()) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "学号不能为空");
      }
      if (student.getName() == null || student.getName().isEmpty()) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "姓名不能为空");
      }
      if (student.getGender() == null || student.getGender().isEmpty()) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "性别不能为空");
      }

      // 校验学号是否已存在
      if (studentMapper.findByStuId(student.getStuId()) != null) {
        throw new BusinessException(ResultCode.PARAM_ERROR, "学号 " + student.getStuId() + " 已存在");
      }

      // 设置默认密码为123456
      if (student.getPassword() == null || student.getPassword().isEmpty()) {
        student.setPassword("123456");
      }
    }

    // 批量插入学生
    int rows = studentMapper.batchInsert(students);
    if (rows <= 0) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "批量导入学生失败");
    }

    return Result.success();
  }

  /**
   * 批量导入学生（处理表单提交）
   */
  @PostMapping("/import")
  public Result<Void> importStudents(@RequestParam("students") MultipartFile file) throws IOException {
    if (file.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "上传的文件不能为空");
    }

    // 解析JSON数据
    String content = new String(file.getBytes(), StandardCharsets.UTF_8);
    ObjectMapper objectMapper = new ObjectMapper();
    List<Student> students;
    try {
      students = objectMapper.readValue(content, new TypeReference<List<Student>>() {
      });
    } catch (Exception e) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "解析学生数据失败: " + e.getMessage());
    }

    // 调用原有批量导入逻辑
    return batchImportStudents(students);
  }

  /**
   * 获取学生总数
   */
  @GetMapping("/count")
  public Result<Integer> countStudents() {
    int count = studentMapper.countAll();
    return Result.success(count);
  }
}